<template>
    <div class="new-food">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/life/canteen/food-list" tag="a">菜式管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
            <li v-if="idEdit">编辑菜式</li>
		</nav-header>

        <div class="food-container" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-form 
                :model="addForm" 
                :rules="rules" 
                ref="addForm" 
                label-width="130px" 
                class="add-form" 
                label-position="left">
                <el-form-item label="菜式名称" prop="name">
                    <el-input v-model="addForm.name" maxlength="10" placeholder="请输入菜式名称" style="width:300px"></el-input>
                </el-form-item>
                 <el-form-item label="价格：" prop="money">
                    <el-input-number 
                        class="input-number-text"
                        v-model="addForm.money" 
                        controls-position="right" 
                        :min="0.01" 
                        :step="0.01"
                        :precision="2"
                        placeholder="请输入价格"
                        style="width:300px">
                    </el-input-number>
                </el-form-item>
                <el-form-item label="菜式图片" prop="picture">
                    <uploader class="uploader-example" 
                        ref="uploaderImg" 
                        :autoStart="false"
                        :options="uploadOptionsImg"
                        :file-status-text="statusText" 
                        @file-added="fileAddImg"
                        @file-removed="fileRemovedImg"
                        @file-success="fileSuccessImg"
                        @file-error="fileFailImg">
                        <uploader-unsupport></uploader-unsupport>
                        <uploader-btn class="format-ifno" :directory="false" :attrs="attrsImg" v-if="selectFileShowImg" :single="true">
                            <i class="el-icon-plus"></i>
                        </uploader-btn>
                        <uploader-list></uploader-list>
                        <div class="uploader-close-box" v-show="addForm.picture" style="background: #fff">
                            <img v-if="addForm.picture" :src="BASE_URL + addForm.picture" class="avatar">
                            <label class="el-upload-list__item-status-label" @click="pictureRemove">
                                <transition name="el-fade-in-linear">
                                    <i class="el-icon-upload-success el-icon-check"></i>
                                </transition>
                                <transition name="el-fade-in-linear">
                                    <i class="el-icon-close"></i>
                                </transition>
                            </label>
                        </div>
                    </uploader>
                </el-form-item>
                <el-form-item style="margin-top: 50px;"> 
                    <el-button type="primary" @click="resetForm" plain>取消</el-button>
                    <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-dialog
			title="图片设置"
			:visible.sync="cropperViews"
			width="1000px"
			custom-class="croppering"
			:before-close="clearFilet"
			:close-on-click-modal="false">
			<div class="croppering">
				<div class="cropper">
					<vueCropper
						ref="cropper"
						:img="imgOption.img"
						:outputSize="imgOption.size"
						:outputType="imgOption.outputType"
						:info="true"
						:full="imgOption.full"
						:canMove="imgOption.canMove"
						:canMoveBox="imgOption.canMoveBox"
						:fixedBox="imgOption.fixedBox"
						:original="imgOption.original"
						:autoCrop="imgOption.autoCrop"
						:autoCropWidth="imgOption.autoCropWidth"
						:autoCropHeight="imgOption.autoCropHeight"
						:centerBox="imgOption.centerBox"
						:high="imgOption.high"
						:infoTrue="imgOption.infoTrue"
						:enlarge="imgOption.enlarge">
					</vueCropper>
				</div>
                <div slot="footer" class="dialog-footer cropper_btn">
                    <el-button  @click="clearFilet()">取消</el-button>
                    <el-button type="primary" @click="finish('base64')">确定</el-button>
                </div>
			</div>
		</el-dialog>
    </div>
</template>

<script>
import { VueCropper }  from 'vue-cropper';
import {dataURLtoFile, uploaderFileFail} from './../../../tools/tool';

export default {
    data() {
        return {
            idEdit: false, // 是否编辑状态
            cropperViews: false, // 是否显示图片裁剪的模态框
            selectFileShowImg: true, //是否显示选择文件按钮
            selectFileOrNotImg: false, //是否选中文件
            previewImgUrl: '',
            UploaderImg: null,
            imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
            loading: {
                status: false,
                txt: '保存数据...'
            },
            addForm: {
                name: undefined,
                picture: undefined,
                money: undefined,
            },
            attrsImg: {
                accept: ['image/*']
            },
            uploadOptionsImg: {
                target: this.BASE_URL + "/api/video/thumbnail_upload",
                testChunks: false,
                headers: { 
                    Authorization: `Bearer ` + this.$g.access_token 
                }
            },
            statusText: {
                success: "上传成功",
                error: "上传出错",
                uploading: "正在上传...",
                paused: "暂停",
                waiting: "等待上传..."
            },
            imgOption: { // vue-cropper 参数配置
                img: '', // 裁剪图片的地址
                size: 1, // 裁剪生成图片的质量
                full: false, // 是否输出原图比例的截图
                outputType: 'png', //输出图片格式
                canMove: true, //能否拖动图片
                fixedBox: true, //截图框固定大小
                original: false, //否显示原始宽高
                canMoveBox: true,  //能否拖动截图框
                autoCrop: true, //autoCrop 是否自动生成截图框
                // 只有自动截图开启 宽度高度才生效
                autoCropWidth: 390,
                autoCropHeight: 220,
                centerBox: false, //截图框是否限制在图片里
                high: true //是否根据dpr生成适合屏幕的高清图片
            },
            rules: {
                name: [
                    { required: true, message: '请输入菜式名称', trigger: ['blur', 'change'] }
                ],
                picture: [
                    { required: true, message: '请输入菜式图片', trigger: ['blur', 'change'] }
                ],
                money: [
                    { required: true, message: '请输入价格', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.idEdit = this.$route.params.id ? true : false;

        if (this.idEdit) {
            this.getInfo();
        }
    },
    mounted() {
        this.UploaderImg = this.$refs.uploaderImg.uploader;
    },
    components: {
        VueCropper
    },
    methods: {
        /**
         * 获取菜单详情
         */
        getInfo() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;

                if (!is_empty(res.data)) {
                    this.addForm = {
                        name: res.data.name,
                        picture: res.data.path,
                        money: res.data.price,
                    }
                }
            })
            const params = {
                id: this.$route.params.id
            }

            this.$ajax.get('api/carte/menusingle', {params, func: {success: success}})
        },
        /**
         * 保存菜单
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                console.log();
                if (valid) {
                    if (this.idEdit) {
                        let yes = (res => {
                            this.saveInfo();
                        })
                        let cancel = (res => {
                            this.resetForm();
                        })

                        this.e_confirm({yes: yes, cancel: cancel, txt: '是否要保存菜式信息修改?'});
                    } else {
                        this.saveInfo();
                    }
                } else {
                    return false;
                }
            })
        },
        saveInfo() {
            this.loading.status = true;

            let params = {
                name: this.addForm.name,
                price: this.addForm.money,
                path: this.addForm.picture,
            }

            const success = (res => {
                this.$message.success(res.msg);
                this.resetForm();
            })
            const fail = (res => {
                this.$message.error(res.msg);
                this.loading.status = false;
            })
            
            if (this.idEdit) {
                params.id = this.$route.params.id;
                this.$ajax.put("api/carte/menusingle", params, {func: {success: success, fail: fail}});
            } else {
                this.$ajax.post("api/carte/menusingle", params, {func: {success: success, fail: fail}});
            }
        },
        /**
         * 返回上一级
         */
        resetForm() {
            this.$router.go(-1);
        },
        pictureRemove() {
            this.UploaderImg.cancel();
            this.addForm.picture = '';
            this.previewImgUrl = '';
            this.selectFileOrNotImg = false;
            this.selectFileShowImg = true;
            this.$refs.addForm.validateField('picture'); 
        },
        /**
         * 图片裁剪后替换原图片
         */
        finish(type) {
            if (type === 'blob') {
                this.$refs.cropper.getCropBlob((data) => {
                    this.cropperViews = false;
                })
            } else {
                this.$refs.cropper.getCropData((data) => {
                    let result = this.$refs.uploaderImg.uploader.fileList;
                    let modelView = dataURLtoFile(data, this.$refs.uploaderImg.uploader.fileList[0].name, 'png');

                    if (modelView.size > 10240000) {
                        this.$message.warning('只允许上传10M以内的文件');
                        this.clearFilet();
                    } else {                        
                        this.$refs.uploaderImg.uploader.fileList[0].file = modelView
                        this.$refs.uploaderImg.uploader.files[0].file = modelView
                        this.$refs.uploaderImg.uploader.fileList[0].size = modelView.size
                        this.$refs.uploaderImg.uploader.files[0].size = modelView.size

                        this.$refs.uploaderImg.uploader.fileList[0].fileType = 'image/png';
                        this.$refs.uploaderImg.uploader.files[0].fileType = 'image/png';
                        this.$refs.uploaderImg.uploader.fileList[0].name = this.$refs.uploaderImg.uploader.fileList[0].name.split(/(.*)\.[^.]+/).join('') + '.png';
                        this.$refs.uploaderImg.uploader.files[0].name = this.$refs.uploaderImg.uploader.fileList[0].name.split(/(.*)\.[^.]+/).join('') + '.png';
                        this.$refs.uploaderImg.uploader.fileList[0].relativePath = this.$refs.uploaderImg.uploader.fileList[0].relativePath.split(/(.*)\.[^.]+/).join('') + '.png';
                        this.$refs.uploaderImg.uploader.files[0].relativePath = this.$refs.uploaderImg.uploader.fileList[0].relativePath.split(/(.*)\.[^.]+/).join('') + '.png';
                        this.$refs.uploaderImg.uploader.fileList[0].uniqueIdentifier = modelView.size+"-"+this.$refs.uploaderImg.uploader.fileList[0].name;
                        this.$refs.uploaderImg.uploader.fileList[0].chunks[0].endByte = modelView.size;

                        this.previewImgURL = data;
                        this.cropperViews = false;
                        this.selectFileOrNotImg = true;
                        this.selectFileShowImg = false;

                        this.fileUpload();
                    }
                })
            }
        },
        /**
         * 上传图片
         */
        fileUpload() {
            this.$refs.uploaderImg.uploader.upload();
        },
        /**
         * 清空上传控件列表的数据
         */
        clearFilet() {
            this.cropperViews = false;
            this.$refs.uploaderImg.uploader.fileList = [];
            this.$refs.uploaderImg.uploader.files = [];
        },
        /**
         * 添加图片
         */
        fileAddImg(file, fileList) {
            let file_type = file.fileType.toLocaleLowerCase();

            if (!this.imageType.includes(file_type)) {
                this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
            } else {
                this.imgOption.img = window.URL.createObjectURL(file.file)
                this.cropperViews = true;
            }
        },
        /**
         * 移除图片
         */
        fileRemovedImg(file) {
            this.previewImgUrl = '';
            this.selectFileOrNotImg = false;
            this.selectFileShowImg = true;
        },
        /**
         * 图片上传成功的事件
         */
        fileSuccessImg(rootFile, file, message, chunk) {
            var mess = eval("(" + message + ")");
            mess = handleResponseData( mess );
            
            if (parseInt(mess.data.status) === 1) {
                this.addForm.picture =  mess.data.file_path;
                this.$refs.addForm.validateField('picture'); 
            }
        },
        fileFailImg(rootFile, file, message, chunk) {
            uploaderFileFail(this, this.UploaderImg, file, message);
        },
    },
}
</script>

<style lang="scss">
.new-food {
    padding-top: 20px;

    .input-number-text {
        width: 100%;

        >span {
            display: none;
        }

        input {
            text-align: left;
        }
    }

    .croppering {
		.cropper {
			height: 500px;
			
			>div{
				height: 100%;
			}
		}
		
        .dialog-footer {
            padding: 35px 0;
            text-align: center;

            button {
                padding: 10px 30px;
            }
        }

        .vue-cropper {
            position: relative;
            width: 100%;
            height: 500px;
            box-sizing: border-box;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            direction: ltr;
            touch-action: none;
            text-align: left;
            background-image: url("");
        }

        .cropper-box,
        .cropper-box-canvas,
        .cropper-drag-box,
        .cropper-crop-box,
        .cropper-face {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            user-select: none;
        }

        .cropper-box-canvas img {
            position: relative;
            text-align: left;
            user-select: none;
            transform: none;
            max-width: none;
            max-height: none;
        }

        .cropper-box {
            overflow: hidden;
        }

        .cropper-move {
            cursor: move;
        }

        .cropper-crop {
            cursor: crosshair;
        }

        .cropper-modal {
            background: rgba(0, 0, 0, 0.5);
        }
        
        .cropper-view-box {
            display: block;
            overflow: hidden;
            width: 100%;
            height: 100%;
            outline: 1px solid #39f;
            outline-color: rgba(51, 153, 255, 0.75);
            user-select: none;
        }

        .cropper-view-box img {
            user-select: none;
            text-align: left;
            max-width: none;
            max-height: none;
        }

        .cropper-face {
            top: 0;
            left: 0;
            background-color: #fff;
            opacity: 0.1;
        }

        .crop-info {
            position: absolute;
            left: 0px;
            min-width: 65px;
            text-align: center;
            color: white;
            line-height: 20px;
            background-color: rgba(0, 0, 0, 0.8);
            font-size: 12px;
        }

        .crop-line {
            position: absolute;
            display: block;
            width: 100%;
            height: 100%;
            opacity: 0.1;
        }

        .line-w {
            top: -3px;
            left: 0;
            height: 5px;
            cursor: n-resize;
        }

        .line-a {
            top: 0;
            left: -3px;
            width: 5px;
            cursor: w-resize;
        }

        .line-s {
            bottom: -3px;
            left: 0;
            height: 5px;
            cursor: s-resize;
        }

        .line-d {
            top: 0;
            right: -3px;
            width: 5px;
            cursor: e-resize;
        }

        .crop-point {
            position: absolute;
            width: 8px;
            height: 8px;
            opacity: 0.75;
            background-color: #39f;
            border-radius: 100%;
        }

        .point1 {
            top: -4px;
            left: -4px;
            cursor: nw-resize;
        }

        .point2 {
            top: -5px;
            left: 50%;
            margin-left: -3px;
            cursor: n-resize;
        }

        .point3 {
            top: -4px;
            right: -4px;
            cursor: ne-resize;
        }

        .point4 {
            top: 50%;
            left: -4px;
            margin-top: -3px;
            cursor: w-resize;
        }

        .point5 {
            top: 50%;
            right: -4px;
            margin-top: -3px;
            cursor: e-resize;
        }

        .point6 {
            bottom: -5px;
            left: -4px;
            cursor: sw-resize;
        }

        .point7 {
            bottom: -5px;
            left: 50%;
            margin-left: -3px;
            cursor: s-resize;
        }

        .point8 {
            bottom: -5px;
            right: -4px;
            cursor: se-resize;
        }
    }

    .format-ifno {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }
    
    .uploader {
        width: 358px;
        height: 220px;
        border: 1px dotted #ddd;
        border-radius: 4px;
        overflow: hidden;

        .uploader-btn {
            border: none;
            width: 100%;
            height: 100%;
            padding: 0;
            text-align: center;
            i {
                font-size: 60px;
                color: #ddd;
            }
            img {
                width: 100%;
                height: 100%;
            }

        }

        .uploader-close-box {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, .3);
            z-index: 99;

            >img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }

            .el-upload-list__item-status-label {
                display: block;
                position: absolute;
                right: -17px;
                top: -7px;
                width: 46px;
                height: 26px;
                background: #13ce66;
                text-align: center;
                transform: rotate(45deg);
                box-shadow: 0 1px 1px #ccc;

                .el-icon-check {
                    font-size: 12px;
                    margin-top: 12px;
                    color: #fff;
                    transform: rotate(-45deg);
                    font-family: 'element-icons' !important;
                    speak: none;
                    font-style: normal;
                    font-weight: normal;
                    font-variant: normal;
                    text-transform: none;
                    line-height: 1;
                    vertical-align: baseline;
                    display: inline-block;
                    -webkit-font-smoothing: antialiased;
                }

                .el-icon-check:before {
                    content: "\E6DA";
                }

                .el-icon-close {
                    display: none;
                }
            }
        }

        .uploader-close-box:hover {
            .el-upload-list__item-status-label {
                top: -4px;
                right: -15px;
                background: #f56c6c;
                box-shadow: none;
                cursor: pointer;

                .el-icon-check {
                    display: none;
                }

                .el-icon-close {
                    position: absolute;
                    transform: rotate(-45deg);
                    top: 10px;
                    color: #fff;
                    right: 14px;
                    font-family: 'element-icons' !important;
                    speak: none;
                    font-style: normal;
                    font-weight: normal;
                    font-variant: normal;
                    text-transform: none;
                    line-height: 1;
                    vertical-align: baseline;
                    display: inline-block;
                    -webkit-font-smoothing: antialiased;
                }

                .el-icon-close:before {
                    content: "\E6DB";
                }
            }
        }

        .uploader-list {
            position: relative;
            height: 100%;
            background: rgba(0,0,0,.4);
            .uploader-file {
                position: relative;
                width: 76%;
                height: 100%;
                margin: 0 auto;
                border-bottom: none;
                overflow: hidden;
            }
            .uploader-file-progress {
                height: 10px;
                top: 58px;
                background: #3ce642;
            }
            .uploader-file-info {
                height: 49px;
                line-height: 49px;
                margin-top: 60px;
                font-size: 12px;
                color: #fff;
                z-index: 1;
            }

            .uploader-file-info:hover {
                background-color: transparent;
            }

            .uploader-file-name,.uploader-file-meta {
                display: none;
            }
            .uploader-file-size {
                width: 40%;
                text-indent: 0;
            }
            .uploader-file-status {
                width: 48%;
                text-indent: 0;
            }
            .uploader-file-actions {
                .uploader-file-remove {
                    position: absolute;
                    width: 24px;
                    height: 24px;
                    line-height: 24px;
                    border-radius: 50%;
                    color: #fff;
                    text-align: center;
                    margin: 0;
                    background: #ef5c5c;
                    top: 50%;
                    transform: translateY(-50%);
                    &::before {
                        display: inline-block;
                        content: 'x';
                    }
                }
            }
        }
    }
}
</style>